package com.ctk.wifi.a.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;


public class UDPSocketSend {
	private DatagramSocket dSocket = null;
	private String msg;
	public UDPSocketSend(String msg)
	{
		super();
		this.msg = msg;
	}
	public void send(String ip,int port)
	{
		InetAddress local = null;
		//获取目标IP地址
		try {
			local = InetAddress.getByName(ip);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//创建UDP Socket
		try {
			dSocket = new DatagramSocket();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//正在连接服务器
		int msgLen=msg==null?0:msg.length();
		DatagramPacket dPacket = new DatagramPacket(msg.getBytes(),msgLen,local,port);
		try {
			dSocket.send(dPacket);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//消息发送成功
		dSocket.close();
	}
}
